package com.gddb.xwj.mywiki.service;

import com.gddb.xwj.mywiki.domain.Content;
import com.gddb.xwj.mywiki.domain.Doc;
import com.gddb.xwj.mywiki.domain.DocExample;
import com.gddb.xwj.mywiki.exception.BusinessException;
import com.gddb.xwj.mywiki.exception.BusinessExceptionEnum;
import com.gddb.xwj.mywiki.mapper.ContentMapper;
import com.gddb.xwj.mywiki.mapper.DocMapper;
import com.gddb.xwj.mywiki.mapper.DocMapperCust;
import com.gddb.xwj.mywiki.req.DocQueryReq;
import com.gddb.xwj.mywiki.req.DocSaveReq;
import com.gddb.xwj.mywiki.resp.DocQueryResp;
import com.gddb.xwj.mywiki.resp.PageResp;
import com.gddb.xwj.mywiki.util.CopyUtil;
import com.gddb.xwj.mywiki.util.RedisUtil;
import com.gddb.xwj.mywiki.util.RequestContext;
import com.gddb.xwj.mywiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 描述：文档管理 （直接电子书管理中复制）
 *
 * @author xwj
 * @create 2022-03-19 17:53
 */
@Service
@Slf4j
public class DocService {

    @Resource
    private DocMapper docMapper;

    @Resource
    private SnowFlake snowFlake;

    @Autowired
    private ContentMapper contentMapper;

    @Resource
    private DocMapperCust docMapperCust;

    @Resource
    public RedisUtil redisUtil;

    /**
     * 全量查询 额外加个顺序升序
     * @return
     */
    public List<DocQueryResp> all(DocQueryReq req) {
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        DocExample.Criteria criteria = docExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getEbookId())) {
            criteria.andEbookIdEqualTo(req.getEbookId());
        }
        List<Doc> docList = docMapper.selectByExample(docExample);
        // 列表复制
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;
    }

    /**
     * 分页查询
     * @param req
     * @return
     */
    public PageResp<DocQueryResp> list(DocQueryReq req){
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        DocExample.Criteria criteria = docExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        //只会对第一个遇到的select生效
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Doc> docList = docMapper.selectByExample(docExample);
        // 列表复制
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        //注意点 PageInfo<DocQueryResp> pageInfo = new PageInfo<>(list); 如果pageinfo用的是DocQueryResp 则返回的是分页的总数 必须为doc才是全部
        log.info("总行数 :{}", pageInfo.getTotal());
        log.info("总页数 :{}", pageInfo.getPages());

        PageResp<DocQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     * @param req
     */
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        Content content = CopyUtil.copy(req, Content.class);
        if(ObjectUtils.isEmpty(req.getId())){
            //新增
            doc.setId(snowFlake.nextId());
            //传递Null 无法促发数据表default0 手工置0
            doc.setViewCount(0);
            doc.setVoteCount(0);
            docMapper.insert(doc);

            content.setId(doc.getId());
            contentMapper.insert(content);
        }else{
            //修改
            docMapper.updateByPrimaryKey(doc);
            int i = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            //如果没有更新则插入
            if(i == 0){
                contentMapper.insert(content);
            }
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(Long id) {
        docMapper.deleteByPrimaryKey(id);
    }

    /**
     * 一组ID删除 减少服务器压力
     * @param list
     */
    public void delete(List<Long> list) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(list);
        docMapper.deleteByExample(docExample);
    }

    /**
     * 查找富文本内容
     * @param id
     * @return
     */
    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        // 文档阅读数+1
        docMapperCust.increaseViewCount(id);
        if(ObjectUtils.isEmpty(content)){
            return "";
        }
        return content.getContent();
    }

    /**
     * 根据id查找
     * @param ebookId
     * @return
     */
    public List<DocQueryResp> findByEbookId(Long ebookId) {
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        docExample.setOrderByClause("sort asc");
        List<Doc> docList = docMapper.selectByExample(docExample);

        // 列表复制
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;
    }


    public void vote(Long id) {
        // docMapperCust.increaseVoteCount(id);
        // 远程IP+doc.id作为key，24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 24 * 60 *60)) {
            docMapperCust.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionEnum.VOTE_REPEAT);
        }
    }
}
